home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / public / fax / src / libtiff / tif_dirread.c < prev    next >
C/C++ Source or Header  |  1994-08-01  |  36KB  |  1,272 lines

  1. #ifndef lint
  2. static char rcsid[] = "$Header: /usr/people/sam/tiff/libtiff/RCS/tif_dirread.c,v 1.38 93/06/28 16:17:12 sam Exp $";
  3. #endif
  4.  
  5. /*
  6.  * Copyright (c) 1988, 1989, 1990, 1991, 1992 Sam Leffler
  7.  * Copyright (c) 1991, 1992 Silicon Graphics, Inc.
  8.  *
  9.  * Permission to use, copy, modify, distribute, and sell this software and 
  10.  * its documentation for any purpose is hereby granted without fee, provided
  11.  * that (i) the above copyright notices and this permission notice appear in
  12.  * all copies of the software and related documentation, and (ii) the names of
  13.  * Sam Leffler and Silicon Graphics may not be used in any advertising or
  14.  * publicity relating to the software without the specific, prior written
  15.  * permission of Sam Leffler and Silicon Graphics.
  16.  * 
  17.  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
  18.  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
  19.  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
  20.  * 
  21.  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
  22.  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  23.  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  24.  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
  25.  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  26.  * OF THIS SOFTWARE.
  27.  */
  28.  
  29. /*
  30.  * TIFF Library.
  31.  *
  32.  * Directory Read Support Routines.
  33.  *
  34.  * NB: Beware of the varargs declarations for routines in
  35.  *     this file.  The names and types of variables has been
  36.  *     carefully chosen to make things work with compilers that
  37.  *     are busted in one way or another (e.g. SGI/MIPS).
  38.  */
  39. #include "tiffiop.h"
  40.  
  41. #define    IGNORE    0        /* tag placeholder used below */
  42.  
  43. #if HAVE_IEEEFP
  44. #define    TIFFCvtIEEEFloatToNative(tif, n, fp)
  45. #endif
  46.  
  47. #if USE_PROTOTYPES
  48. static    void EstimateStripByteCounts(TIFF *, TIFFDirEntry *, u_int);
  49. static    void MissingRequired(TIFF *, const char *);
  50. static    int CheckDirCount(TIFF *, TIFFDirEntry *, u_long);
  51. static    int TIFFFetchData(TIFF *, TIFFDirEntry *, char *);
  52. static    int TIFFFetchString(TIFF *, TIFFDirEntry *, char *);
  53. static    float TIFFFetchRational(TIFF *, TIFFDirEntry *);
  54. static    int TIFFFetchNormalTag(TIFF *, TIFFDirEntry *);
  55. static    int TIFFFetchPerSampleShorts(TIFF *, TIFFDirEntry *, long *);
  56. static    int TIFFFetchShortArray(TIFF *, TIFFDirEntry *, u_short []);
  57. static    int TIFFFetchStripThing(TIFF *, TIFFDirEntry *, long, u_long **);
  58. static    int TIFFFetchRefBlackWhite(TIFF *, TIFFDirEntry *);
  59. static    int TIFFFetchJPEGQTables(TIFF *, TIFFDirEntry *);
  60. static    int TIFFFetchJPEGCTables(TIFF *, TIFFDirEntry *, u_char ***);
  61. static    int TIFFFetchExtraSamples(TIFF *, TIFFDirEntry *);
  62. static    float TIFFFetchFloat(TIFF *, TIFFDirEntry *);
  63. static    int TIFFFetchFloatArray(TIFF *, TIFFDirEntry *, float *);
  64. static    int TIFFFetchShortPair(TIFF *, TIFFDirEntry *);
  65. #ifdef STRIPCHOP_SUPPORT
  66. static    void ChopUpSingleUncompressedStrip(TIFF *);
  67. #endif
  68. #else
  69. static    void EstimateStripByteCounts();
  70. static    void MissingRequired();
  71. static    int CheckDirCount();
  72. static    int TIFFFetchData();
  73. static    int TIFFFetchString();
  74. static    float TIFFFetchRational();
  75. static    int TIFFFetchNormalTag();
  76. static    int TIFFFetchPerSampleShorts();
  77. static    int TIFFFetchShortArray();
  78. static    int TIFFFetchStripThing();
  79. static    int TIFFFetchRefBlackWhite();
  80. static    int TIFFFetchJPEGQTables();
  81. static    int TIFFFetchJPEGCTables();
  82. static    int TIFFFetchExtraSamples();
  83. static    float TIFFFetchFloat();
  84. static    int TIFFFetchFloatArray();
  85. static    int TIFFFetchShortPair();
  86. #ifdef STRIPCHOP_SUPPORT
  87. static    void ChopUpSingleUncompressedStrip();
  88. #endif
  89. #endif
  90.  
  91. static char *
  92. DECLARE3(CheckMalloc, TIFF*, tif, int, n, char*, what)
  93. {
  94.     char *cp = _TIFFmalloc(n);
  95.     if (cp == NULL)
  96.         TIFFError(tif->tif_name, "No space %s", what);
  97.     return (cp);
  98. }
  99.  
  100. /*
  101.  * Read the next TIFF directory from a file
  102.  * and convert it to the internal format.
  103.  * We read directories sequentially.
  104.  */
  105. int
  106. DECLARE1(TIFFReadDirectory, TIFF*, tif)
  107. {
  108.     register TIFFDirEntry *dp;
  109.     register int n;
  110.     register TIFFDirectory *td;
  111.     TIFFDirEntry *dir;
  112.     long v;
  113.     const TIFFFieldInfo *fip;
  114.     u_short dircount;
  115.     char *cp;
  116.     int diroutoforderwarning = 0;
  117.  
  118.     tif->tif_diroff = tif->tif_nextdiroff;
  119.     if (tif->tif_diroff == 0)        /* no more directories */
  120.         return (0);
  121.     /*
  122.      * Cleanup any previous compression state.
  123.      */
  124.     if (tif->tif_cleanup)
  125.         (*tif->tif_cleanup)(tif);
  126.     tif->tif_curdir++;
  127.     if (!isMapped(tif)) {
  128.         if (!SeekOK(tif, tif->tif_diroff)) {
  129.             TIFFError(tif->tif_name,
  130.                 "Seek error accessing TIFF directory");
  131.             return (0);
  132.         }
  133.         if (!ReadOK(tif, &dircount, sizeof (short))) {
  134.             TIFFError(tif->tif_name,
  135.                 "Can not read TIFF directory count");
  136.             return (0);
  137.         }
  138.         if (tif->tif_flags & TIFF_SWAB)
  139.             TIFFSwabShort(&dircount);
  140.         dir = (TIFFDirEntry *)CheckMalloc(tif,
  141.             dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
  142.         if (dir == NULL)
  143.             return (0);
  144.         if (!ReadOK(tif, dir, dircount*sizeof (TIFFDirEntry))) {
  145.             TIFFError(tif->tif_name, "Can not read TIFF directory");
  146.             goto bad;
  147.         }
  148.         /*
  149.          * Read offset to next directory for sequential scans.
  150.          */
  151.         if (!ReadOK(tif, &tif->tif_nextdiroff, sizeof (long)))
  152.             tif->tif_nextdiroff = 0;
  153.     } else {
  154.         off_t off = tif->tif_diroff;
  155.  
  156.         if (off + sizeof (short) > tif->tif_size) {
  157.             TIFFError(tif->tif_name,
  158.                 "Can not read TIFF directory count");
  159.             return (0);
  160.         } else
  161.             memcpy(&dircount, tif->tif_base + off, sizeof (short));
  162.         off += sizeof (short);
  163.         if (tif->tif_flags & TIFF_SWAB)
  164.             TIFFSwabShort(&dircount);
  165.         dir = (TIFFDirEntry *)CheckMalloc(tif,
  166.             dircount * sizeof (TIFFDirEntry), "to read TIFF directory");
  167.         if (dir == NULL)
  168.             return (0);
  169.         if (off + dircount*sizeof (TIFFDirEntry) > tif->tif_size) {
  170.             TIFFError(tif->tif_name, "Can not read TIFF directory");
  171.             goto bad;
  172.         } else
  173.             memcpy(dir, tif->tif_base + off,
  174.                 dircount*sizeof (TIFFDirEntry));
  175.         off += dircount* sizeof (TIFFDirEntry);
  176.         if (off + sizeof (long) < tif->tif_size)
  177.             memcpy(&tif->tif_nextdiroff, tif->tif_base + off,
  178.                 sizeof (long));
  179.         else
  180.             tif->tif_nextdiroff = 0;
  181.     }
  182.     if (tif->tif_flags & TIFF_SWAB)
  183.         TIFFSwabLong((u_long *)&tif->tif_nextdiroff);
  184.  
  185.     tif->tif_flags &= ~TIFF_BEENWRITING;    /* reset before new dir */
  186.     /*
  187.      * Setup default value and then make a pass over
  188.      * the fields to check type and tag information,
  189.      * and to extract info required to size data
  190.      * structures.  A second pass is made afterwards
  191.      * to read in everthing not taken in the first pass.
  192.      */
  193.     td = &tif->tif_dir;
  194.     /* free any old stuff and reinit */
  195.     TIFFFreeDirectory(tif);
  196.     TIFFDefaultDirectory(tif);
  197.     /*
  198.      * Electronic Arts writes gray-scale TIFF files
  199.      * without a PlanarConfiguration directory entry.
  200.      * Thus we setup a default value here, even though
  201.      * the TIFF spec says there is no default value.
  202.      */
  203.     TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
  204.     for (fip = tiffFieldInfo, dp = dir, n = dircount; n > 0; n--, dp++) {
  205.         if (tif->tif_flags & TIFF_SWAB) {
  206.             TIFFSwabArrayOfShort(&dp->tdir_tag, 2);
  207.             TIFFSwabArrayOfLong(&dp->tdir_count, 2);
  208.         }
  209.         /*
  210.          * Find the field information entry for this tag.
  211.          */
  212.         /*
  213.          * Silicon Beach (at least) writes unordered
  214.          * directory tags (violating the spec).  Handle
  215.          * it here, but be obnoxious (maybe they'll fix it?).
  216.          */
  217.         if (dp->tdir_tag < fip->field_tag) {
  218.             if (!diroutoforderwarning) {
  219.                 TIFFWarning(tif->tif_name,
  220.     "invalid TIFF directory; tags are not sorted in ascending order");
  221.                 diroutoforderwarning = 1;
  222.             }
  223.             fip = tiffFieldInfo;    /* O(n^2) */
  224.         }
  225.         while (fip->field_tag && fip->field_tag < dp->tdir_tag)
  226.             fip++;
  227.         if (!fip->field_tag || fip->field_tag != dp->tdir_tag) {
  228.             TIFFWarning(tif->tif_name,
  229.                 "unknown field with tag %d (0x%x) ignored",
  230.                 dp->tdir_tag,  dp->tdir_tag);
  231.             dp->tdir_tag = IGNORE;
  232.             fip = tiffFieldInfo;    /* restart search */
  233.             continue;
  234.         }
  235.         /*
  236.          * Null out old tags that we ignore.
  237.          */
  238.         if (fip->field_bit == FIELD_IGNORE) {
  239.     ignore:
  240.             dp->tdir_tag = IGNORE;
  241.             continue;
  242.         }
  243.         /*
  244.          * Check data type.
  245.          */
  246.         while (dp->tdir_type != (u_short)fip->field_type) {
  247.             if (fip->field_type == TIFF_ANY)    /* wildcard */
  248.                 break;
  249.             fip++;
  250.             if (!fip->field_tag || fip->field_tag != dp->tdir_tag) {
  251.                 TIFFWarning(tif->tif_name,
  252.                    "wrong data type %d for \"%s\"; tag ignored",
  253.                     dp->tdir_type, fip[-1].field_name);
  254.                 goto ignore;
  255.             }
  256.         }
  257.         /*
  258.          * Check count if known in advance.
  259.          */
  260.         if (fip->field_readcount != TIFF_VARIABLE) {
  261.             u_long expected = (fip->field_readcount == TIFF_SPP) ?
  262.                 (u_long) td->td_samplesperpixel :
  263.                 (u_long) fip->field_readcount;
  264.             if (!CheckDirCount(tif, dp, expected))
  265.                 goto ignore;
  266.         }
  267.  
  268.         switch (dp->tdir_tag) {
  269.         case TIFFTAG_STRIPOFFSETS:
  270.         case TIFFTAG_STRIPBYTECOUNTS:
  271.         case TIFFTAG_TILEOFFSETS:
  272.         case TIFFTAG_TILEBYTECOUNTS:
  273.             TIFFSetFieldBit(tif, fip->field_bit);
  274.             break;
  275.         case TIFFTAG_IMAGEWIDTH:
  276.         case TIFFTAG_IMAGELENGTH:
  277.         case TIFFTAG_IMAGEDEPTH:
  278.         case TIFFTAG_TILELENGTH:
  279.         case TIFFTAG_TILEWIDTH:
  280.         case TIFFTAG_TILEDEPTH:
  281.         case TIFFTAG_PLANARCONFIG:
  282.         case TIFFTAG_SAMPLESPERPIXEL:
  283.         case TIFFTAG_ROWSPERSTRIP:
  284.             if (!TIFFFetchNormalTag(tif, dp))
  285.                 goto bad;
  286.             dp->tdir_tag = IGNORE;
  287.             break;
  288.         case TIFFTAG_EXTRASAMPLES:
  289.             (void) TIFFFetchExtraSamples(tif, dp);
  290.             dp->tdir_tag = IGNORE;
  291.             break;
  292.         }
  293.     }
  294.  
  295.     /*
  296.      * Allocate directory structure and setup defaults.
  297.      */
  298.     if (!TIFFFieldSet(tif, FIELD_IMAGEDIMENSIONS)) {
  299.         MissingRequired(tif, "ImageLength");
  300.         goto bad;
  301.     }
  302.     if (!TIFFFieldSet(tif, FIELD_PLANARCONFIG)) {
  303.         MissingRequired(tif, "PlanarConfiguration");
  304.         goto bad;
  305.     }
  306.     /* 
  307.       * Setup appropriate structures (by strip or by tile)
  308.      */
  309.     if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) {
  310.         td->td_stripsperimage = (td->td_rowsperstrip == 0xffffffff ?
  311.              (td->td_imagelength != 0 ? 1 : 0) :
  312.              howmany(td->td_imagelength, td->td_rowsperstrip));
  313.         td->td_tilewidth = td->td_imagewidth;
  314.         td->td_tilelength = td->td_rowsperstrip;
  315.         td->td_tiledepth = td->td_imagedepth;
  316.         tif->tif_flags &= ~TIFF_ISTILED;
  317.     } else {
  318.         td->td_stripsperimage = TIFFNumberOfTiles(tif);
  319.         tif->tif_flags |= TIFF_ISTILED;
  320.     }
  321.     td->td_nstrips = td->td_stripsperimage;
  322.     if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
  323.         td->td_nstrips *= td->td_samplesperpixel;
  324.     if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) {
  325.         MissingRequired(tif,
  326.             isTiled(tif) ? "TileOffsets" : "StripOffsets");
  327.         goto bad;
  328.     }
  329.  
  330.     /*
  331.      * Second pass: extract other information.
  332.      */
  333.     for (dp = dir, n = dircount; n > 0; n--, dp++) {
  334.         if (dp->tdir_tag == IGNORE)
  335.             continue;
  336.         switch (dp->tdir_tag) {
  337.         case TIFFTAG_COMPRESSION:
  338.         case TIFFTAG_MINSAMPLEVALUE:
  339.         case TIFFTAG_MAXSAMPLEVALUE:
  340.         case TIFFTAG_BITSPERSAMPLE:
  341.             /*
  342.              * The 5.0 spec says the Compression tag has
  343.              * one value, while earlier specs say it has
  344.              * one value per sample.  Because of this, we
  345.              * accept the tag if one value is supplied.
  346.              *
  347.              * The MinSampleValue, MaxSampleValue and
  348.              * BitsPerSample tags are supposed to be written
  349.              * as one value/sample, but some vendors incorrectly
  350.              * write one value only -- so we accept that
  351.              * as well (yech).
  352.              */
  353.             if (dp->tdir_count == 1) {
  354.                 v = TIFFExtractData(tif,
  355.                     dp->tdir_type, dp->tdir_offset);
  356.                 if (!TIFFSetField(tif, dp->tdir_tag, (int)v))
  357.                     goto bad;
  358.                 break;
  359.             }
  360.             /* fall thru... */
  361.         case TIFFTAG_DATATYPE:
  362.         case TIFFTAG_SAMPLEFORMAT:
  363.             if (!TIFFFetchPerSampleShorts(tif, dp, &v) ||
  364.                 !TIFFSetField(tif, dp->tdir_tag, (int)v))
  365.                 goto bad;
  366.             break;
  367.         case TIFFTAG_STRIPOFFSETS:
  368.         case TIFFTAG_TILEOFFSETS:
  369.             if (!TIFFFetchStripThing(tif, dp,
  370.                 td->td_nstrips, &td->td_stripoffset))
  371.                 goto bad;
  372.             break;
  373.         case TIFFTAG_STRIPBYTECOUNTS:
  374.         case TIFFTAG_TILEBYTECOUNTS:
  375.             if (!TIFFFetchStripThing(tif, dp,
  376.                 td->td_nstrips, &td->td_stripbytecount))
  377.                 goto bad;
  378.             break;
  379.         case TIFFTAG_COLORMAP:
  380.         case TIFFTAG_TRANSFERFUNCTION:
  381.             /*
  382.              * TransferFunction can have either 1x or 3x data
  383.              * values; Colormap can have only 3x items.
  384.              */
  385.             v = 1L<<td->td_bitspersample;
  386.             if (dp->tdir_tag == TIFFTAG_COLORMAP ||
  387.                 dp->tdir_count != v) {
  388.                 if (!CheckDirCount(tif, dp, 3*v))
  389.                     break;
  390.             }
  391.             v *= sizeof (u_short);
  392.             cp = CheckMalloc(tif,
  393.                 dp->tdir_count * sizeof (u_short),
  394.                 "to read \"TransferFunction\" tag");
  395.             if (cp != NULL) {
  396.                 if (TIFFFetchData(tif, dp, cp)) {
  397.                     /*
  398.                      * This deals with there being only
  399.                      * one array to apply to all samples.
  400.                      */
  401.                     if (dp->tdir_count == (1L<<td->td_bitspersample))
  402.                         v = 0;
  403.                     TIFFSetField(tif, dp->tdir_tag,
  404.                         cp, cp+v, cp+2*v);
  405.                 }
  406.                 _TIFFfree(cp);
  407.             }
  408.             break;
  409.         case TIFFTAG_PAGENUMBER:
  410.         case TIFFTAG_HALFTONEHINTS:
  411.         case TIFFTAG_YCBCRSUBSAMPLING:
  412.         case TIFFTAG_DOTRANGE:
  413.             (void) TIFFFetchShortPair(tif, dp);
  414.             break;
  415. #ifdef COLORIMETRY_SUPPORT
  416.         case TIFFTAG_REFERENCEBLACKWHITE:
  417.             (void) TIFFFetchRefBlackWhite(tif, dp);
  418.             break;
  419. #endif
  420. #ifdef JPEG_SUPPORT
  421.         case TIFFTAG_JPEGQTABLES:
  422.             if (TIFFFetchJPEGQTables(tif, dp))
  423.                 TIFFSetFieldBit(tif, FIELD_JPEGQTABLES);
  424.             break;
  425.         case TIFFTAG_JPEGDCTABLES:
  426.             if (TIFFFetchJPEGCTables(tif, dp, &td->td_dctab))
  427.                 TIFFSetFieldBit(tif, FIELD_JPEGDCTABLES);
  428.             break;
  429.         case TIFFTAG_JPEGACTABLES:
  430.             if (TIFFFetchJPEGCTables(tif, dp, &td->td_actab))
  431.                 TIFFSetFieldBit(tif, FIELD_JPEGACTABLES);
  432.             break;
  433. #endif
  434. /* BEGIN REV 4.0 COMPATIBILITY */
  435.         case TIFFTAG_OSUBFILETYPE:
  436.             v = 0;
  437.             switch (TIFFExtractData(tif, dp->tdir_type,
  438.                 dp->tdir_offset)) {
  439.             case OFILETYPE_REDUCEDIMAGE:
  440.                 v = FILETYPE_REDUCEDIMAGE;
  441.                 break;
  442.             case OFILETYPE_PAGE:
  443.                 v = FILETYPE_PAGE;
  444.                 break;
  445.             }
  446.             if (v)
  447.                 (void) TIFFSetField(tif,
  448.                     TIFFTAG_SUBFILETYPE, (int)v);
  449.             break;
  450. /* END REV 4.0 COMPATIBILITY */
  451.         default:
  452.             (void) TIFFFetchNormalTag(tif, dp);
  453.             break;
  454.         }
  455.     }
  456.     /*
  457.      * Verify Palette image has a Colormap.
  458.      */
  459.     if (td->td_photometric == PHOTOMETRIC_PALETTE &&
  460.         !TIFFFieldSet(tif, FIELD_COLORMAP)) {
  461.         MissingRequired(tif, "Colormap");
  462.         goto bad;
  463.     }
  464.     /*
  465.      * Attempt to deal with a missing StripByteCounts tag.
  466.      */
  467.     if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) {
  468.         /*
  469.          * Some manufacturers violate the spec by not giving
  470.          * the size of the strips.  In this case, assume there
  471.          * is one uncompressed strip of data.
  472.          */
  473.         if (td->td_nstrips > 1) {
  474.             MissingRequired(tif, "StripByteCounts");
  475.             goto bad;
  476.         }
  477.         TIFFWarning(tif->tif_name,
  478. "TIFF directory is missing required \"%s\" field, calculating from imagelength",
  479.             TIFFFieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
  480.         EstimateStripByteCounts(tif, dir, dircount);
  481. #define    BYTECOUNTLOOKSBAD \
  482.     (td->td_stripbytecount[0] == 0 || \
  483.     (td->td_compression == COMPRESSION_NONE && \
  484.      td->td_stripbytecount[0] > TIFFGetFileSize(tif) - td->td_stripoffset[0]))
  485.     } else if (td->td_nstrips == 1 && BYTECOUNTLOOKSBAD) {
  486.         /*
  487.          * Plexus (and others) sometimes give a value
  488.          * of zero for a tag when they don't know what
  489.          * the correct value is!  Try and handle the
  490.          * simple case of estimating the size of a one
  491.          * strip image.
  492.          */
  493.         TIFFWarning(tif->tif_name,
  494.         "Bogus \"%s\" field, ignoring and calculating from imagelength",
  495.             TIFFFieldWithTag(TIFFTAG_STRIPBYTECOUNTS)->field_name);
  496.         EstimateStripByteCounts(tif, dir, dircount);
  497.     }
  498.     if (dir)
  499.         _TIFFfree((char *)dir);
  500.     if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE))
  501.         td->td_maxsamplevalue = (1L<<td->td_bitspersample)-1;
  502.     /*
  503.      * Setup default compression scheme.
  504.      */
  505.     if (!TIFFFieldSet(tif, FIELD_COMPRESSION))
  506.         TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
  507. #ifdef STRIPCHOP_SUPPORT
  508.         /*
  509.          * Some manufacturers make life difficult by writing
  510.      * large amounts of uncompressed data as a single strip.
  511.      * This is contrary to the recommendations of the spec.
  512.          * The following makes an attempt at breaking such images
  513.      * into strips closer to the recommended 8k bytes.  A
  514.      * side effect, however, is that the RowsPerStrip tag
  515.      * value may be changed.
  516.          */
  517.         if (td->td_nstrips == 1 && td->td_compression == COMPRESSION_NONE &&
  518.         td->td_tilewidth == td->td_imagewidth)
  519.         ChopUpSingleUncompressedStrip(tif);
  520. #endif
  521.     /*
  522.      * Reinitialize i/o since we are starting on a new directory.
  523.      */
  524.     tif->tif_row = -1;
  525.     tif->tif_curstrip = -1;
  526.     tif->tif_col = -1;
  527.     tif->tif_curtile = -1;
  528.     tif->tif_tilesize = TIFFTileSize(tif);
  529.     tif->tif_scanlinesize = TIFFScanlineSize(tif);
  530.     return (1);
  531. bad:
  532.     if (dir)
  533.         _TIFFfree((char *)dir);
  534.     return (0);
  535. }
  536.  
  537. static void
  538. DECLARE3(EstimateStripByteCounts, TIFF*, tif, TIFFDirEntry*, dir, u_int, dircount)
  539. {
  540.     register TIFFDirEntry *dp;
  541.     register TIFFDirectory *td = &tif->tif_dir;
  542.     register int n;
  543.  
  544.     td->td_stripbytecount = (u_long *)
  545.         CheckMalloc(tif, sizeof (u_long), "for \"StripByteCounts\" array");
  546.     if (td->td_compression != COMPRESSION_NONE) {
  547.         u_long space = sizeof (TIFFHeader)
  548.             + sizeof (short)
  549.             + (dircount * sizeof (TIFFDirEntry))
  550.             + sizeof (long);
  551.         long filesize = TIFFGetFileSize(tif);
  552.         /* calculate amount of space used by indirect values */
  553.         for (dp = dir, n = dircount; n > 0; n--, dp++) {
  554.             int cc = dp->tdir_count * tiffDataWidth[dp->tdir_type];
  555.             if (cc > sizeof (long))
  556.                 space += cc;
  557.         }
  558.         td->td_stripbytecount[0] = filesize - space;
  559.         /*
  560.          * This gross hack handles the case were the offset to
  561.          * the strip is past the place where we think the strip
  562.          * should begin.  Since a strip of data must be contiguous,
  563.          * it's safe to assume that we've overestimated the amount
  564.          * of data in the strip and trim this number back accordingly.
  565.          */ 
  566.         if (td->td_stripoffset[0] + td->td_stripbytecount[0] > filesize)
  567.             td->td_stripbytecount[0] =
  568.                 filesize - td->td_stripoffset[0];
  569.     } else {
  570.         u_long rowbytes = howmany(td->td_bitspersample *
  571.             td->td_samplesperpixel * td->td_imagewidth, 8);
  572.         td->td_stripbytecount[0] = td->td_imagelength * rowbytes;
  573.     }
  574.     TIFFSetFieldBit(tif, FIELD_STRIPBYTECOUNTS);
  575.     if (!TIFFFieldSet(tif, FIELD_ROWSPERSTRIP))
  576.         td->td_rowsperstrip = td->td_imagelength;
  577. }
  578.  
  579. static void
  580. DECLARE2(MissingRequired, TIFF*, tif, const char*, tagname)
  581. {
  582.     TIFFError(tif->tif_name,
  583.         "TIFF directory is missing required \"%s\" field", tagname);
  584. }
  585.  
  586. /*
  587.  * Check the count field of a directory
  588.  * entry against a known value.  The caller
  589.  * is expected to skip/ignore the tag if
  590.  * there is a mismatch.
  591.  */
  592. static int
  593. DECLARE3(CheckDirCount, TIFF*, tif, TIFFDirEntry*, dir, u_long, count)
  594. {
  595.     if (count != dir->tdir_count) {
  596.         TIFFWarning(tif->tif_name,
  597.     "incorrect count for field \"%s\" (%lu, expecting %lu); tag ignored",
  598.             TIFFFieldWithTag(dir->tdir_tag)->field_name,
  599.             dir->tdir_count, count);
  600.         return (0);
  601.     }
  602.     return (1);
  603. }
  604.  
  605. /*
  606.  * Fetch a contiguous directory item.
  607.  */
  608. static int
  609. DECLARE3(TIFFFetchData, TIFF*, tif, TIFFDirEntry*, dir, char*, cp)
  610. {
  611.     int cc, w;
  612.  
  613.     w = tiffDataWidth[dir->tdir_type];
  614.     cc = dir->tdir_count * w;
  615.     if (!isMapped(tif)) {
  616.         if (!SeekOK(tif, dir->tdir_offset))
  617.             goto bad;
  618.         if (!ReadOK(tif, cp, cc))
  619.             goto bad;
  620.     } else {
  621.         if (dir->tdir_offset + cc > tif->tif_size)
  622.             goto bad;
  623.         memcpy(cp, tif->tif_base + dir->tdir_offset, cc);
  624.     }
  625.     if (tif->tif_flags & TIFF_SWAB) {
  626.         switch (dir->tdir_type) {
  627.         case TIFF_SHORT:
  628.         case TIFF_SSHORT:
  629.             TIFFSwabArrayOfShort((u_short *)cp, dir->tdir_count);
  630.             break;
  631.         case TIFF_LONG:
  632.         case TIFF_SLONG:
  633.         case TIFF_FLOAT:
  634.             TIFFSwabArrayOfLong((u_long *)cp, dir->tdir_count);
  635.             break;
  636.         case TIFF_RATIONAL:
  637.         case TIFF_SRATIONAL:
  638.             TIFFSwabArrayOfLong((u_long *)cp, 2*dir->tdir_count);
  639.             break;
  640.         }
  641.     }
  642.     return (cc);
  643. bad:
  644.     TIFFError(tif->tif_name, "Error fetching data for field \"%s\"",
  645.         TIFFFieldWithTag(dir->tdir_tag)->field_name);
  646.     return (0);
  647. }
  648.  
  649. /*
  650.  * Fetch an ASCII item from the file.
  651.  */
  652. static int
  653. DECLARE3(TIFFFetchString, TIFF*, tif, TIFFDirEntry*, dir, char*, cp)
  654. {
  655.     if (dir->tdir_count <= 4) {
  656.         u_long l = dir->tdir_offset;
  657.         if (tif->tif_flags & TIFF_SWAB)
  658.             TIFFSwabLong(&l);
  659.         memcpy(cp, &l, dir->tdir_count);
  660.         return (1);
  661.     }
  662.     return (TIFFFetchData(tif, dir, cp));
  663. }
  664.  
  665. /*
  666.  * Convert numerator+denominator to float.
  667.  */
  668. static int
  669. DECLARE5(cvtRational, TIFF*, tif, TIFFDirEntry*, dir, u_long, num, u_long, denom, float*, rv)
  670. {
  671.     if (denom == 0) {
  672.         TIFFError(tif->tif_name,
  673.             "%s: Rational with zero denominator (num = %lu)",
  674.             TIFFFieldWithTag(dir->tdir_tag)->field_name, num);
  675.         return (0);
  676.     } else {
  677.         if (dir->tdir_type == TIFF_RATIONAL)
  678.             *rv = ((float)num / (float)denom);
  679.         else
  680.             *rv = ((float)(long)num / (float)(long)denom);
  681.         return (1);
  682.     }
  683. }
  684.  
  685. /*
  686.  * Fetch a rational item from the file
  687.  * at offset off and return the value
  688.  * as a floating point number.
  689.  */
  690. static float
  691. DECLARE2(TIFFFetchRational, TIFF*, tif, TIFFDirEntry*, dir)
  692. {
  693.     u_long l[2];
  694.     float v;
  695.  
  696.     return (!TIFFFetchData(tif, dir, (char *)l) ||
  697.         !cvtRational(tif, dir, l[0], l[1], &v) ? 1. : v);
  698. }
  699.  
  700. /*
  701.  * Fetch a single floating point value
  702.  * from the offset field and return it
  703.  * as a native float.
  704.  */
  705. static float
  706. DECLARE2(TIFFFetchFloat, TIFF*, tif, TIFFDirEntry*, dir)
  707. {
  708.     float v = (float)
  709.         TIFFExtractData(tif, dir->tdir_type, dir->tdir_offset);
  710.     TIFFCvtIEEEFloatToNative(tif, 1, &v);
  711.     return (v);
  712. }
  713.  
  714. /*
  715.  * Fetch an array of BYTE or SBYTE values.
  716.  */
  717. static int
  718. DECLARE3(TIFFFetchByteArray, TIFF*, tif, TIFFDirEntry*, dir, u_short*, v)
  719. {
  720.  
  721.     if (dir->tdir_count <= 4) {
  722.         /*
  723.          * Extract data from offset field.
  724.          */
  725.         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  726.             switch (dir->tdir_count) {
  727.             case 4: v[3] = dir->tdir_offset & 0xff;
  728.             case 3: v[2] = (dir->tdir_offset >> 8) & 0xff;
  729.             case 2: v[1] = (dir->tdir_offset >> 16) & 0xff;
  730.             case 1: v[0] = dir->tdir_offset >> 24;
  731.             }
  732.         } else {
  733.             switch (dir->tdir_count) {
  734.             case 4: v[3] = dir->tdir_offset >> 24;
  735.             case 3: v[2] = (dir->tdir_offset >> 16) & 0xff;
  736.             case 2: v[1] = (dir->tdir_offset >> 8) & 0xff;
  737.             case 1: v[0] = dir->tdir_offset & 0xff;
  738.             }
  739.         }
  740.         return (1);
  741.     } else
  742.         return (TIFFFetchData(tif, dir, (char *)v));    /* XXX */
  743. }
  744.  
  745. /*
  746.  * Fetch an array of SHORT or SSHORT values.
  747.  */
  748. static int
  749. DECLARE3(TIFFFetchShortArray, TIFF*, tif, TIFFDirEntry*, dir, u_short*, v)
  750. {
  751.     if (dir->tdir_count <= 2) {
  752.         if (tif->tif_header.tiff_magic == TIFF_BIGENDIAN) {
  753.             switch (dir->tdir_count) {
  754.             case 2: v[1] = dir->tdir_offset & 0xffff;
  755.             case 1: v[0] = dir->tdir_offset >> 16;
  756.             }
  757.         } else {
  758.             switch (dir->tdir_count) {
  759.             case 2: v[1] = dir->tdir_offset >> 16;
  760.             case 1: v[0] = dir->tdir_offset & 0xffff;
  761.             }
  762.         }
  763.         return (1);
  764.     } else
  765.         return (TIFFFetchData(tif, dir, (char *)v));
  766. }
  767.  
  768. /*
  769.  * Fetch a pair of SHORT or BYTE values.
  770.  */
  771. static int
  772. DECLARE2(TIFFFetchShortPair, TIFF*, tif, TIFFDirEntry*, dir)
  773. {
  774.     u_short v[2];
  775.     int ok = 0;
  776.  
  777.     switch (dir->tdir_type) {
  778.     case TIFF_SHORT:
  779.     case TIFF_SSHORT:
  780.         ok = TIFFFetchShortArray(tif, dir, v);
  781.         break;
  782.     case TIFF_BYTE:
  783.     case TIFF_SBYTE:
  784.         ok  = TIFFFetchByteArray(tif, dir, v);
  785.         break;
  786.     }
  787.     if (ok)
  788.         TIFFSetField(tif, dir->tdir_tag, v[0], v[1]);
  789.     return (ok);
  790. }
  791.  
  792. /*
  793.  * Fetch an array of LONG or SLONG values.
  794.  */
  795. static int
  796. DECLARE3(TIFFFetchLongArray, TIFF*, tif, TIFFDirEntry*, dir, u_long*, v)
  797. {
  798.     if (dir->tdir_count == 1) {
  799.         v[0] = dir->tdir_offset;
  800.         return (1);
  801.     } else
  802.         return (TIFFFetchData(tif, dir, (char *)v));
  803. }
  804.  
  805. /*
  806.  * Fetch an array of RATIONAL or SRATIONAL values.
  807.  */
  808. static int
  809. DECLARE3(TIFFFetchRationalArray, TIFF*, tif, TIFFDirEntry*, dir, float*, v)
  810. {
  811.     int ok = 0;
  812.     u_long *l;
  813.  
  814.     l = (u_long *)CheckMalloc(tif,
  815.         dir->tdir_count*tiffDataWidth[dir->tdir_type],
  816.         "to fetch array of rationals");
  817.     if (l) {
  818.         if (TIFFFetchData(tif, dir, (char *)l)) {
  819.             u_long i;
  820.             for (i = 0; i < dir->tdir_count; i++) {
  821.                 ok = cvtRational(tif, dir,
  822.                     l[2*i+0], l[2*i+1], &v[i]);
  823.                 if (!ok)
  824.                     break;
  825.             }
  826.         }
  827.         _TIFFfree((char *)l);
  828.     }
  829.     return (ok);
  830. }
  831.  
  832. /*
  833.  * Fetch an array of FLOAT values.
  834.  */
  835. static int
  836. DECLARE3(TIFFFetchFloatArray, TIFF*, tif, TIFFDirEntry*, dir, float*, v)
  837. {
  838.     if (TIFFFetchData(tif, dir, (char *)v)) {
  839.         TIFFCvtIEEEFloatToNative(tif, dir->tdir_count, v);
  840.         return (1);
  841.     } else
  842.         return (0);
  843. }
  844.  
  845. /*
  846.  * Fetch a tag that is not handled by special case code.
  847.  *
  848.  * NB: DOUBLE and UNDEFINED types are not handled.
  849.  */
  850. static int
  851. DECLARE2(TIFFFetchNormalTag, TIFF*, tif, TIFFDirEntry*, dp)
  852. {
  853.     static char mesg[] = "to fetch tag value";
  854.     int ok = 0;
  855.  
  856.     if (dp->tdir_count > 1) {        /* array of values */
  857.         char *cp = NULL;
  858.  
  859.         switch (dp->tdir_type) {
  860.         case TIFF_BYTE:
  861.         case TIFF_SBYTE:
  862.             /* NB: always expand BYTE values to shorts */
  863.             cp = CheckMalloc(tif,
  864.                 dp->tdir_count * sizeof (u_short), mesg);
  865.             ok = cp && TIFFFetchByteArray(tif, dp, (u_short *)cp);
  866.             break;
  867.         case TIFF_SHORT:
  868.         case TIFF_SSHORT:
  869.             cp = CheckMalloc(tif,
  870.                 dp->tdir_count * sizeof (u_short), mesg);
  871.             ok = cp && TIFFFetchShortArray(tif, dp, (u_short *)cp);
  872.             break;
  873.         case TIFF_LONG:
  874.         case TIFF_SLONG:
  875.             cp = CheckMalloc(tif,
  876.                 dp->tdir_count * sizeof (u_long), mesg);
  877.             ok = cp && TIFFFetchLongArray(tif, dp, (u_long *)cp);
  878.             break;
  879.         case TIFF_RATIONAL:
  880.         case TIFF_SRATIONAL:
  881.             cp = CheckMalloc(tif,
  882.                 dp->tdir_count * sizeof (float), mesg);
  883.             ok = cp && TIFFFetchRationalArray(tif, dp, (float *)cp);
  884.             break;
  885.         case TIFF_FLOAT:
  886.             cp = CheckMalloc(tif,
  887.                 dp->tdir_count * sizeof (float), mesg);
  888.             ok = cp && TIFFFetchFloatArray(tif, dp, (float *)cp);
  889.             break;
  890.         case TIFF_ASCII:
  891.             /*
  892.              * Some vendors write strings w/o the trailing
  893.              * NULL byte, so always append one just in case.
  894.              */
  895.             cp = CheckMalloc(tif, dp->tdir_count+1, mesg);
  896.             if (ok = (cp && TIFFFetchString(tif, dp, cp)))
  897.                 cp[dp->tdir_count] = '\0';    /* XXX */
  898.             break;
  899.         }
  900.         if (ok)
  901.             ok = TIFFSetField(tif, dp->tdir_tag, cp);
  902.         if (cp != NULL)
  903.             _TIFFfree(cp);
  904.     } else if (CheckDirCount(tif, dp, 1)) {    /* singleton value */
  905.         char c[2];
  906.         TIFFDataType type;
  907.         switch (dp->tdir_type) {
  908.         case TIFF_BYTE:
  909.         case TIFF_SBYTE:
  910.         case TIFF_SHORT:
  911.         case TIFF_SSHORT:
  912.             /*
  913.              * If the tag is also acceptable as a LONG or SLONG
  914.              * then TIFFSetField will expect a long parameter
  915.              * passed to it (through varargs).  Thus, for machines
  916.              * where sizeof (int) != sizeof (long) we must do
  917.              * a careful check here.  It's hard to say if this
  918.              * is worth optimizing.
  919.              *
  920.              * NB: We use TIFFFieldWithTag here knowing that
  921.              *     it returns us the first entry in the table
  922.              *     for the tag and that that entry is for the
  923.              *     widest potential data type the tag may have.
  924.              */
  925.             type = TIFFFieldWithTag(dp->tdir_tag)->field_type;
  926.             if (type != TIFF_LONG && type != TIFF_SLONG) {
  927.                 ok = TIFFSetField(tif, dp->tdir_tag, (int)
  928.               TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset));
  929.                 break;
  930.             }
  931.             /* fall thru... */
  932.         case TIFF_LONG:
  933.         case TIFF_SLONG:
  934.             ok = TIFFSetField(tif, dp->tdir_tag, (u_long)
  935.           TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset));
  936.             break;
  937.         case TIFF_RATIONAL:
  938.         case TIFF_SRATIONAL:
  939.             ok = TIFFSetField(tif, dp->tdir_tag,
  940.                 TIFFFetchRational(tif, dp));
  941.             break;
  942.         case TIFF_FLOAT:
  943.             ok = TIFFSetField(tif, dp->tdir_tag,
  944.                 TIFFFetchFloat(tif, dp));
  945.             break;
  946.         case TIFF_ASCII:
  947.             if (ok = (TIFFFetchString(tif, dp, c))) {
  948.                 c[1] = '\0';        /* XXX paranoid */
  949.                 ok = TIFFSetField(tif, dp->tdir_tag, c);
  950.             }
  951.             break;
  952.         }
  953.     }
  954.     return (ok);
  955. }
  956.  
  957. #define    NITEMS(x)    (sizeof (x) / sizeof (x[0]))
  958. /*
  959.  * Fetch samples/pixel short values for 
  960.  * the specified tag and verify that
  961.  * all values are the same.
  962.  */
  963. static int
  964. DECLARE3(TIFFFetchPerSampleShorts, TIFF*, tif, TIFFDirEntry*, dir, long*, pl)
  965. {
  966.     int samples = tif->tif_dir.td_samplesperpixel;
  967.     int status = 0;
  968.  
  969.     if (CheckDirCount(tif, dir, (u_long)samples)) {
  970.         u_short buf[10], *v = buf;
  971.  
  972.         if (samples > NITEMS(buf))
  973.             v = (u_short *)_TIFFmalloc(samples * sizeof (u_short));
  974.         if (TIFFFetchShortArray(tif, dir, v)) {
  975.             int i;
  976.             for (i = 1; i < samples; i++)
  977.                 if (v[i] != v[0]) {
  978.                     TIFFError(tif->tif_name,
  979.         "Cannot handle different per-sample values for field \"%s\"",
  980.                    TIFFFieldWithTag(dir->tdir_tag)->field_name);
  981.                     goto bad;
  982.                 }
  983.             *pl = v[0];
  984.             status = 1;
  985.         }
  986.     bad:
  987.         if (v != buf)
  988.             _TIFFfree((char *)v);
  989.     }
  990.     return (status);
  991. }
  992. #undef NITEMS
  993.  
  994. /*
  995.  * Fetch a set of offsets or lengths.
  996.  * While this routine says "strips",
  997.  * in fact it's also used for tiles.
  998.  */
  999. static int
  1000. DECLARE4(TIFFFetchStripThing, TIFF*, tif, TIFFDirEntry*, dir, long, nstrips, u_long**, lpp)
  1001. {
  1002.     register u_long *lp;
  1003.     int status;
  1004.  
  1005.     if (!CheckDirCount(tif, dir, nstrips))
  1006.         return (0);
  1007.     /*
  1008.      * Allocate space for strip information.
  1009.      */
  1010.     if (*lpp == NULL &&
  1011.         (*lpp = (u_long *)CheckMalloc(tif,
  1012.           nstrips * sizeof (u_long), "for strip array")) == NULL)
  1013.         return (0);
  1014.     lp = *lpp;
  1015.     if (dir->tdir_type == (int)TIFF_SHORT) {
  1016.         /*
  1017.          * Handle short->long expansion.
  1018.          */
  1019.         u_short *dp = (u_short *)CheckMalloc(tif,
  1020.             dir->tdir_count* sizeof (u_short), "to fetch strip tag");
  1021.         if (dp == NULL)
  1022.             return (0);
  1023.         if (status = TIFFFetchShortArray(tif, dir, dp)) {
  1024.             register u_short *wp = dp;
  1025.             while (nstrips-- > 0)
  1026.                 *lp++ = *wp++;
  1027.         }
  1028.         _TIFFfree((char *)dp);
  1029.     } else
  1030.         status = TIFFFetchLongArray(tif, dir, lp);
  1031.     return (status);
  1032. }
  1033.  
  1034. #ifdef COLORIMETRY_SUPPORT
  1035. static int
  1036. DECLARE2(TIFFFetchRefBlackWhite, TIFF*, tif, TIFFDirEntry*, dir)
  1037. {
  1038.     static char mesg[] = "for \"ReferenceBlackWhite\" array";
  1039.     char *cp;
  1040.     int ok;
  1041.  
  1042.     if (dir->tdir_type == TIFF_RATIONAL)
  1043.         return (TIFFFetchNormalTag(tif, dir));
  1044.     /*
  1045.      * Handle LONG's for backward compatibility.
  1046.      */
  1047.     cp = CheckMalloc(tif, dir->tdir_count * sizeof (u_long), mesg);
  1048.     if (ok = (cp && TIFFFetchLongArray(tif, dir, (u_long *)cp))) {
  1049.         float *fp = (float *)
  1050.             CheckMalloc(tif, dir->tdir_count * sizeof (float), mesg);
  1051.         if (ok = (fp != NULL)) {
  1052.             int i;
  1053.             for (i = 0; i < dir->tdir_count; i++)
  1054.                 fp[i] = (float)((u_long *)cp)[i];
  1055.             ok = TIFFSetField(tif, dir->tdir_tag, fp);
  1056.             _TIFFfree((char *)fp);
  1057.         }
  1058.     }
  1059.     if (cp)
  1060.         _TIFFfree(cp);
  1061.     return (ok);
  1062. }
  1063. #endif
  1064.  
  1065. #ifdef JPEG_SUPPORT
  1066. /*
  1067.  * Fetch the JPEG Quantization tables
  1068.  * for the specified directory entry.
  1069.  * Storage for the td_qtab array is
  1070.  * allocated as a side effect.
  1071.  */
  1072. static int
  1073. DECLARE2(TIFFFetchJPEGQTables, TIFF*, tif, TIFFDirEntry*, dir)
  1074. {
  1075.     TIFFDirectory *td = &tif->tif_dir;
  1076.     long off[4];
  1077.     int i, j;
  1078.     TIFFDirEntry tdir;
  1079.     char *qmat;
  1080.  
  1081.     if (dir->tdir_count > 1) {
  1082.         /* XXX verify count <= 4 */
  1083.         if (!TIFFFetchData(tif, dir, (char *)off))
  1084.             return (0);
  1085.     } else
  1086.         off[0] = dir->tdir_offset;
  1087.     /*
  1088.      * We don't share per-component q matrices because
  1089.      * (besides complicating this logic even more), it
  1090.      * would make it very painful if the user does a ``set''.
  1091.      */
  1092.     td->td_qtab = (u_char **)CheckMalloc(tif,
  1093.         dir->tdir_count*(sizeof (u_char *) + 64*sizeof (u_char)),
  1094.         "for JPEG Q table");
  1095.     if (td->td_qtab == NULL)
  1096.         return (0);
  1097.     tdir.tdir_type = TIFF_BYTE;
  1098.     tdir.tdir_count = 64;
  1099.     qmat = (((char *)td->td_qtab) + dir->tdir_count*sizeof (u_char *));
  1100.     for (i = 0; i < dir->tdir_count; i++) {
  1101.         td->td_qtab[i] = (u_char *)qmat;
  1102.         tdir.tdir_offset = off[i];
  1103.         if (!TIFFFetchData(tif, &tdir, qmat))
  1104.             return (0);
  1105.         qmat += 64*sizeof (u_char);
  1106.     }
  1107.     return (1);
  1108. }
  1109.  
  1110. /*
  1111.  * Fetch JPEG Huffman code tables for the
  1112.  * specified directory entry.  Storage for
  1113.  * the tables are allocated as a side effect.
  1114.  */
  1115. static int
  1116. DECLARE3(TIFFFetchJPEGCTables, TIFF*, tif, TIFFDirEntry*, dir, u_char***, ptab)
  1117. {
  1118.     long off[4];
  1119.     int i, j, ncodes;
  1120.     TIFFDirEntry tdir;
  1121.     char *tab;
  1122.  
  1123.     if (dir->tdir_count > 1) {
  1124.         /* XXX verify count <= 4 */
  1125.         if (!TIFFFetchData(tif, dir, (char *)off))
  1126.             return (0);
  1127.     } else
  1128.         off[0] = dir->tdir_offset;
  1129.     /*
  1130.      * We don't share per-component tables because
  1131.      * (besides complicating this logic even more), it
  1132.      * would make it very painful if the user does a
  1133.      * ``set''.  Note also that we don't try to optimize
  1134.      * storage of the tables -- we just allocate enough
  1135.      * space to hold the largest possible.  All this
  1136.      * stuff is so complicated 'cuz the tag is defined
  1137.      * to be compatible with the JPEG table format,
  1138.      * rather than something that fits well into the
  1139.      * structure of TIFF -- argh!
  1140.      */
  1141.     *ptab = (u_char **)CheckMalloc(tif, dir->tdir_count*
  1142.         (sizeof (u_char *) + (16+256)*sizeof (u_char)),
  1143.         "for JPEG Huffman table");
  1144.     if (*ptab == NULL)
  1145.         return (0);
  1146.     tdir.tdir_type = TIFF_BYTE;
  1147.     tab = (((char *)*ptab) + dir->tdir_count*sizeof (u_char *));
  1148.     for (i = 0; i < dir->tdir_count; i++) {
  1149.         (*ptab)[i] = (u_char *)tab;
  1150.         tdir.tdir_offset = off[i];
  1151.         tdir.tdir_count = 16;
  1152.         /*
  1153.          * We must fetch the array that holds the
  1154.          * count of codes for each bit length first
  1155.          * and the count up the number of codes that
  1156.          * are in the variable length table.  This
  1157.          * information is implicit in the JPEG format
  1158.          * 'cuz it's preceded by a length field.
  1159.          */
  1160.         if (!TIFFFetchData(tif, &tdir, tab))    /* count array */
  1161.             return (0);
  1162.         for (ncodes = 0, j = 0; j < 16; j++)
  1163.             ncodes += tab[j];
  1164.         /*
  1165.          * Adjust offsets and fetch codes separately.
  1166.          */
  1167.         tdir.tdir_offset += 16;
  1168.         tdir.tdir_count = ncodes;
  1169.         tab += 16;
  1170.         if (!TIFFFetchData(tif, &tdir, tab))
  1171.             return (0);
  1172.         tab += ncodes;
  1173.     }
  1174.     return (1);
  1175. }
  1176. #endif
  1177.  
  1178. /*
  1179.  * Accept matteing-only ExtraSamples tag.
  1180.  */
  1181. static int
  1182. DECLARE2(TIFFFetchExtraSamples, TIFF*, tif, TIFFDirEntry*, dp)
  1183. {
  1184.     int type;
  1185.     
  1186.     if (dp->tdir_count != 1) {
  1187.         TIFFError(tif->tif_name,
  1188.             "Can not handle more than 1 extra sample/pixel");
  1189.         return (0);
  1190.     }
  1191.     type = TIFFExtractData(tif, dp->tdir_type, dp->tdir_offset);
  1192.     if (type != EXTRASAMPLE_ASSOCALPHA) {
  1193.         TIFFError(tif->tif_name,
  1194.             "Can only handle associated-alpha extra samples");
  1195.         return (0);
  1196.     }
  1197.     return (TIFFSetField(tif, TIFFTAG_MATTEING, 1));
  1198. }
  1199.  
  1200. #ifdef STRIPCHOP_SUPPORT
  1201. /*
  1202.  * Replace a single strip (tile) of uncompressed data by
  1203.  * multiple strips (tiles), each approximately 8Kbytes.
  1204.  * This is useful for dealing with large images or
  1205.  * for dealing with machines with a limited amount
  1206.  * memory.
  1207.  */
  1208. static void
  1209. DECLARE1(ChopUpSingleUncompressedStrip, TIFF*, tif)
  1210. {
  1211.     register TIFFDirectory *td = &tif->tif_dir;
  1212.     u_long bytecount = td->td_stripbytecount[0];
  1213.     u_long offset = td->td_stripoffset[0];
  1214.     u_long rowbytes = TIFFVTileSize(tif, 1);
  1215.     u_long strip, stripbytes;
  1216.     u_long nstrips, rowsperstrip;
  1217.     u_long *newcounts, *newoffsets;
  1218.  
  1219.     /*
  1220.      * Make the rows hold at least one
  1221.      * scanline, but fill 8k if possible.
  1222.      */
  1223.     if (rowbytes > 8192) {
  1224.         stripbytes = rowbytes;
  1225.         rowsperstrip = 1;
  1226.     } else {
  1227.         rowsperstrip = 8192 / rowbytes;
  1228.         stripbytes = rowbytes * rowsperstrip;
  1229.     }
  1230.     nstrips = howmany(bytecount, stripbytes);
  1231.     newcounts = (u_long *) CheckMalloc(tif, nstrips * sizeof (u_long),
  1232.                 "for chopped \"StripByteCounts\" array");
  1233.     newoffsets = (u_long *) CheckMalloc(tif, nstrips * sizeof (u_long),
  1234.                 "for chopped \"StripOffsets\" array");
  1235.     if (newcounts == NULL || newoffsets == NULL) {
  1236.             /*
  1237.          * Unable to allocate new strip information, give
  1238.          * up and use the original one strip information.
  1239.          */
  1240.         if (newcounts != NULL)
  1241.             _TIFFfree(newcounts);
  1242.         if (newoffsets != NULL)
  1243.             _TIFFfree(newoffsets);
  1244.         return;
  1245.     }
  1246.     /*
  1247.      * Fill the strip information arrays with
  1248.      * new bytecounts and offsets that reflect
  1249.      * the broken-up format.
  1250.      */
  1251.     for (strip = 0; strip < nstrips; strip++) {
  1252.         if (stripbytes > bytecount)
  1253.             stripbytes = bytecount;
  1254.         newcounts[strip] = stripbytes;
  1255.         newoffsets[strip] = offset;
  1256.         offset += stripbytes;
  1257.         bytecount -= stripbytes;
  1258.     }
  1259.     /*
  1260.      * Replace old single strip info with multi-strip info.
  1261.      */
  1262.     td->td_stripsperimage = td->td_nstrips = nstrips;
  1263.     td->td_rowsperstrip = rowsperstrip;
  1264.     td->td_tilelength = rowsperstrip;
  1265.  
  1266.     _TIFFfree(td->td_stripbytecount);
  1267.     _TIFFfree(td->td_stripoffset);
  1268.     td->td_stripbytecount = newcounts;
  1269.     td->td_stripoffset = newoffsets;
  1270. }
  1271. #endif /* STRIPCHOP_SUPPORT */
  1272.